package com.hunliji.monitor.share.component.redis.impl;

import com.hunliji.monitor.share.component.redis.RedisAddAndSubtractFacade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * redis 加减操作
 * @author wuchen
 */
@Slf4j
@Component
public class RedisAddAndSubtractFacadeImpl implements RedisAddAndSubtractFacade {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 默认的过期时间 单位：秒
     */
    private static final Long DEFAULT_EXPIRES = 120L;


    @Override
    public Long increment(String key, Long value) {
        return increment(key,value,DEFAULT_EXPIRES);
    }


    @Override
    public Long increment(String key, Long value, Long expires) {
        if(value<0){
            throw new RuntimeException("递增因子必须大于0");
        }
        Long result = stringRedisTemplate.opsForValue().increment(key, value);
        stringRedisTemplate.expire(key,expires, TimeUnit.SECONDS);
        return result;
    }

    @Override
    public Long decrement(String key, Long value) {
        return decrement(key,value,DEFAULT_EXPIRES);
    }

    @Override
    public Long decrement(String key, Long value, Long expires) {
        if(value<0){
            throw new RuntimeException("递减因子必须大于0");
        }
        Long result = stringRedisTemplate.opsForValue().decrement(key, value);
        stringRedisTemplate.expire(key,expires, TimeUnit.SECONDS);
        return result;
    }
}
